import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_update_dialog/update_dialog.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';

import '../model/EcyApiCommonResponse.dart';
import 'EcyRequestBaseManager.dart';

class EcyVersion {

  String _version = "1.0";
  late bool _needUpdate = false;
  late UpdateDialog? dialog;
  late Map<String, dynamic>? _lastest;

  void getVersion(BuildContext context) async {
    var response = await EcyRequestbasemanager().get(
        "/app/api/app/commons/version", {"type": Platform.isIOS ? "2" : "1"});
    if (response != null) {
      var commonResponse =
      EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        PackageInfo packageInfo = await PackageInfo.fromPlatform();
        String version = packageInfo.version;
        Map<String, dynamic> lastest = response["data"];
        bool u = true;
        try {
          u = int.parse(packageInfo.version.replaceAll(".", "")) >= int.parse(lastest["versionCode"].replaceAll(".", ""));
        } catch (e) {
          u = true;
        }
        _version = version;
        _needUpdate = !u;
        _lastest = lastest;

        showUpdaterAlert(context);
      }
    }
  }

  void showUpdaterAlert(BuildContext context) {
    if (_needUpdate) {
      dialog = UpdateDialog.showUpdate(context,
          title: _lastest?["versionTitle"] ?? ("版本升级" + _lastest?["versionCode"]),
          updateContent: _lastest?["versionContent"] ?? "", onUpdate: () {
            launchAppStore();
          }
          );
    }
  }

  Future<void> launchAppStore() async {
    const appStoreUrl = 'itms-apps://itunes.apple.com/app/id6741015928'; // iOS
    const playStoreUrl =
        'market://details?id=com.ecy.app.ecy_app_flutter'; // Android
    final url = Platform.isIOS ? appStoreUrl : playStoreUrl;
    if (Platform.isIOS) {
      if (await canLaunchUrl(Uri.parse(url))) {
        await launchUrl(Uri.parse(url));
      } else {
        const webUrl = 'https://www.goodsqi.com/h5/html/download.html';
        final url2 = Platform.isIOS
            ? (_lastest?["iosUrl"] ?? webUrl)
            : (_lastest?["apkUrl"] ?? webUrl);
        // 无法打开应用商店，跳转到网页版
        await launchUrl(Uri.parse(url2));
      }
    } else {
      await launchUrl(
          Uri.parse((_lastest?["apkUrl"]) ?? "https://www.pgyer.com/VBS0GMTT"));
    }
  }


}
